// 项目管理  API
var express = require('express');
var router = express.Router();
const app = express()
const cors = require('cors');
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 日志：
const computingLog = require('../../middlewares/computingLog')
const ProjectModel = require('../../Models/ProjectModel');
// 获取数据库数据
router.get('/FetchProjects', computingLog, function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // 或指定为 'http://localhost:8080'
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // 获取数据库数据
  ProjectModel.find().sort({ time: -1 }).then((data) => {
    // const enumValues = SQSchema.path('type').enumValues;
    // console.log(enumValues);
    res.json({
      code: '0000',
      msg: '获取成功',
      data: data
    })
  }).catch((err) => {
    res.json({
      code: '1001',
      msg: '获取失败',
      data: []
    })
    return
  })
})

// 删除一条项目数据
router.delete('/DeleProject/:id', computingLog, function (req, res) {
  res.header('Access-Control-Allow-Origin', '*'); // 或指定为 'http://localhost:8080'
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  let id = req.params.id
  ProjectModel.deleteOne({ _id: id }).then((data) => {
    res.json({
      code: '0000',
      msg: '删除成功',
      data: ''
    })
  }).catch((err) => {
    res.json({
      code: '1002',
      msg: '删除失败',
      data: null
    })
    return
  })
})

// 添加项目数据
router.post('/AddProject', computingLog, function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // 或指定为 'http://localhost:8080'
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // 获取数据库数据
  // console.log("收到数据：", req.body);
  ProjectModel.create({ ...req.body }).then((data) => {
    res.json({
      code: '0000',
      msg: '添加成功',
      data: data
    })
  }).catch(() => {
    res.json({
      code: '2006',
      msg: '添加失败',
      data: null
    })
    return
  })
})

// 编辑更新单条项目数据
router.patch('/UpdataProject/:id', computingLog, (req, res) => {
  res.header('Access-Control-Allow-Origin', '*'); // 或指定为 'http://localhost:8080'
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  let id = req.params.id
  ProjectModel.updateOne({ _id: id }, req.body).then((data) => {
    ProjectModel.findById(id).then((data) => {
      res.json({
        code: "0000",
        msg: '更新成功了',
        data: data
      })
    }).catch((err) => {
      res.json({
        code: "2006",
        msg: "更新失败",
        data: null
      })
    })
  })
})

module.exports = router;